package org.nightrunner.d3.service.impl;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import org.nightrunner.d3.dao.ICategoryDao;
import org.nightrunner.d3.entity.Category;
import org.nightrunner.d3.model.DefaultPaginationInfo;
import org.nightrunner.d3.model.IPaginationInfo;
import org.nightrunner.d3.model.PaginationModel;
import org.nightrunner.d3.service.ICategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * Category Service implementation
 * 
 * @author NigthRunner
 * @date 2012-7-26
 * @version 1.0
 */

@Service
public class CategoryService implements ICategoryService {

	@Autowired
	private ICategoryDao categoryDao;

	public ICategoryDao getCategoryDao() {
		return categoryDao;
	}

	public void setCategoryDao(ICategoryDao categoryDao) {
		this.categoryDao = categoryDao;
	}

	public Serializable addCategory(Category category) {
		return categoryDao.save(category);
	}

	public Category getCategory(String bureauId) {
		return categoryDao.get(bureauId);
	}

	public List<Category> getAllCategory() {
		return categoryDao.list();
	}

	public void deleteCategory(Category category) {
		categoryDao.delete(category);
	}

	public PaginationModel<List<Category>> getCategory() {
		IPaginationInfo paginationInfo = new DefaultPaginationInfo();
		paginationInfo.setCurrentPage(0);
		paginationInfo.setRowSize(10);
		return getCategory(paginationInfo);
	}

	public PaginationModel<List<Category>> getCategory(
			IPaginationInfo pagination) {
		return categoryDao.find(pagination);
	}

	public void updateCategory(Category category) {
		categoryDao.merge(category);
	}

	public List<Category> getSuperCategoryChain(Category category) {
		List<Category> categorys = new ArrayList<Category>(3);
		boolean loop = true;
		while (loop) {
			if (category.getSuperCategory() == null) {
				loop = false;
			} else {
				categorys.add(category.getSuperCategory());
				category = category.getSuperCategory();
			}
		}
		List<Category> sortedCategorys = new ArrayList<Category>();
		for (int i = categorys.size() - 1; i >= 0; i--) {
			sortedCategorys.add(categorys.get(i));
		}
		return sortedCategorys;
	}
}
